#!/bin/bash

echo "========================================"
echo "启动鸥鹏超级面试官系统服务"
echo "========================================"

echo ""
echo "1. 检查Redis服务状态..."
if ! redis-cli ping > /dev/null 2>&1; then
    echo "❌ Redis服务未运行，请先启动Redis服务"
    echo "💡 提示：可以通过以下方式启动Redis："
    echo "   - Ubuntu/Debian: sudo systemctl start redis-server"
    echo "   - macOS (Homebrew): brew services start redis"
    echo "   - 手动启动: redis-server"
    echo "   - 或者使用Docker: docker run -d -p 6379:6379 redis"
    exit 1
else
    echo "✅ Redis服务运行正常"
fi

echo ""
echo "2. 启动Celery Worker（后台任务处理）..."
# 在后台启动Celery Worker
nohup python -m celery -A inter_api worker --loglevel=info > celery.log 2>&1 &
CELERY_PID=$!
echo "Celery Worker PID: $CELERY_PID"

echo ""
echo "3. 等待Celery Worker启动..."
sleep 3

echo ""
echo "4. 启动Django开发服务器..."
echo "按 Ctrl+C 停止服务器"
echo ""

# 创建停止脚本
cat > stop_services.sh << 'EOF'
#!/bin/bash
echo "停止所有服务..."

# 停止Django服务器（通过Ctrl+C或kill）
echo "停止Django服务器..."

# 停止Celery Worker
echo "停止Celery Worker..."
pkill -f "celery.*worker"

# 清理日志文件（可选）
# rm -f celery.log

echo "✅ 所有服务已停止"
EOF

chmod +x stop_services.sh

# 设置信号处理，当脚本被中断时停止Celery
trap 'echo ""; echo "正在停止服务..."; kill $CELERY_PID 2>/dev/null; exit 0' INT TERM

# 启动Django服务器（前台运行）
python manage.py runserver 0.0.0.0:8000

echo ""
echo "========================================"
echo "🎉 Django服务器已停止"
echo "========================================"
echo ""
echo "💡 如需停止Celery Worker，请运行: ./stop_services.sh"
